package cn.tedu.mall.seckill.interceptor;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.pojo.seckill.dto.SeckillOrderAddDTO;
import cn.tedu.mall.seckill.service.Impl.SeckillSkuServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 执行redis减库存，防止大量请求访问数据库
 * 来一个请求redis中对应key值的value就减一，直到减到-1，再阻止这次请求
 */
@Component
@Order(20)
public class RedisStockInterceptor implements SeckillInterceptor{
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 每个sku都是一个秒杀订单提交的商品数据
     * 每个sku在redis中同步了数据库的库存 seckill:sku:stock:{skuId} {quantity}
     * 每次调用这个方法，对已经存在的库存数据做decr操作
     * 如果返回值是负数，则拦截
     * @param seckillOrderAddDTO
     */
    @Override
    public void seckillCommitCheck(SeckillOrderAddDTO seckillOrderAddDTO) {
        Long skuId = seckillOrderAddDTO.getSeckillOrderItemAddDTO().getSkuId();
        Long stock = stringRedisTemplate.opsForValue().decrement(SeckillSkuServiceImpl.SECKILL_SKU_STOCK_PREFIX + skuId);
        if (stock < 0) {
            throw new CoolSharkServiceException(ResponseCode.FORBIDDEN, "秒杀库存不足！");
        }
    }
}
